<!-- index.vue -->
<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="审批请求ID" prop="approvalRequestsId">
        <el-input
          v-model="queryParams.approvalRequestsId"
          placeholder="请输入审批请求ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请求日期" prop="requestDate">
        <el-date-picker clearable
                        v-model="queryParams.requestDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择请求日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审批日期" prop="approvalDate">
        <el-date-picker clearable
                        v-model="queryParams.approvalDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择审批日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审批结果" prop="brand">
        <el-select v-model="queryParams.approvalResult" placeholder="审批结果" clearable>
          <el-option
            v-for="vehicle in delRequestsStatus"
            :key="vehicle.dictSort"
            :label="vehicle.dictLabel"
            :value="vehicle.dictSort"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地点" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['approval:approval:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 审批请求列表 -->
    <el-table v-loading="loading" :data="approvalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="审批请求ID" align="center" prop="approvalRequestsId" />
      <el-table-column label="请求信息" align="center" prop="requestInfo" />
      <el-table-column label="请求日期" align="center" prop="requestDate" width="180" />
      <el-table-column label="审批日期" align="center" prop="approvalDate" width="180"/>
      <el-table-column label="审批结果" align="center" prop="approvalResult" >
        <template slot-scope="scope">
          <span>{{ getStatusText(scope.row.approvalResult) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请求者姓名" align="center" prop="requesterName" />
      <el-table-column label="审批者姓名" align="center" prop="approverName" />
      <el-table-column label="地点" align="center" prop="location" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.approvalResult !== 0"
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            v-hasPermi="['approval:approval:query']"
          >查看详情</el-button>
          <el-button
            v-if="scope.row.approvalResult === 0"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['approval:approval:edit']"
          >拒绝</el-button>
          <el-button
            v-if="scope.row.approvalResult === 0"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['approval:approval:remove']"
          >通过</el-button>
          <el-button
            v-if="scope.row.approvalResult === 1"
            size="mini"
            type="text"
            @click="handlePickup(scope.row)"
            v-hasPermi="['approval:records:add']"
          >我要提车</el-button>
          <el-button
            v-if="scope.row.approvalResult === 3"
            size="mini"
            type="text"
            @click="handleReturnCar(scope.row)"
            v-hasPermi="['approval:records:remove']"
          >我要还车</el-button>
          <el-button
            v-if="scope.row.approvalResult === 3||scope.row.approvalResult === 4"
            size="mini"
            type="text"
            @click="handleExecuteDetail(scope.row)"
            v-hasPermi="['approval:records:query']"
          >执行详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 拒绝原因对话框 -->
    <el-dialog :title="rejectTitle" :visible.sync="rejectDialogOpen" width="300px" append-to-body>
      <el-form ref="rejectForm" :model="rejectForm" :rules="rejectRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="rejectionReason">
          <el-input v-model="rejectForm.rejectionReason" type="textarea" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增审批请求对话框 -->
    <el-dialog :title="title" :visible.sync="addDialogOpen" width="800px" append-to-body>
      <AddApproval :open.sync="addDialogOpen" @submit="handleAddSubmit" />
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :title="detailTitle" :visible.sync="detailDialogOpen" width="800px" append-to-body>
      <ApprovalDetail :open.sync="detailDialogOpen" :detailForm="detailForm" />
    </el-dialog>

    <!-- 选择车辆对话框 -->
    <SelectVehicleDialog :open.sync="selectVehicleDialogOpen" @submit="handleVehicleSelection" />

    <!-- 提车对话框 -->
    <PickupDialog :open.sync="pickupDialogOpen" :row="pickupRow" @submit="handlePickupSubmit" />

    <!-- 执行详情对话框 -->
    <el-dialog :title="executionDialogTitle" :visible.sync="executionDetailDialogOpen" width="800px" append-to-body>
      <ExecutionDetailDialog :open.sync="executionDetailDialogOpen"  :form="executionDetailForm" />
    </el-dialog>
  </div>
</template>

<script>
import { listApproval, getApproval, delApproval, updateApproval} from "@/api/approval/approval";
import { getRecords, delRecords, addRecords } from "@/api/approval/records";
import SelectVehicleDialog from "@/views/vehicles/vehicles/SelectVehicleDialog.vue";
import AddApproval from './AddApproval.vue';
import ApprovalDetail from './ApprovalDetail.vue';
import PickupDialog from './PickupDialog.vue'; // 引入提车对话框组件
import ExecutionDetailDialog from './ExecutionDetailDialog.vue'; // 引入执行详情对话框组件
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Approval",
  components: {
    SelectVehicleDialog,
    AddApproval,
    ApprovalDetail,
    PickupDialog,
    ExecutionDetailDialog // 注册执行详情对话框组件
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批请求表格数据
      approvalList: [],
      // 弹出层标题
      title: "",
      detailTitle: "",
      executionDialogTitle: "",
      // 是否显示新增对话框
      addDialogOpen: false,
      // 是否显示详情对话框
      detailDialogOpen: false,
      // 是否显示执行详情对话框
      executionDetailDialogOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        approvalRequestsId: null,
        requestDate: null,
        approvalDate: null,
        approvalResult: null,
        location: null
      },
      selectVehicleDialogOpen: false,
      // 表单参数
      form: {
        sysVehicles: [],
        requestInfo: null,
        requestDate: null,
        rejectionReason: null,
        location: null,
        driver: null
      },
      // 详情表单参数
      detailForm: {
        sysVehicles: [],
        approvalRequestsId: null,
        requestInfo: null,
        requestDate: null,
        approvalDate: null,
        approvalResult: null,
        rejectionReason: null,
        requesterName: null,
        approverName: null,
        location: null
      },
      // 执行详情表单参数
      executionDetailForm: {
        approvalRequestId: null,
        actualStartTime: null,
        actualEndTime: null,
        status: null,
        remarks: null,
        sysVechicleDto: []
      },
      // 表单校验
      rules: {
        sysVehicles: [
          { required: true, message: '请选择车辆', trigger: 'change' }
        ],
        requestInfo: [
          { required: true, message: '请输入请求信息', trigger: 'blur' }
        ],
        requestDate: [
          { required: true, message: '请选择使用时间', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入地点', trigger: 'blur' }
        ]
      },
      delRequestsStatus:{},
      // 拒绝原因对话框相关属性
      rejectDialogOpen: false,
      rejectTitle: "拒绝原因",
      rejectForm: {
        approvalRequestsId: null, // 保存当前审批请求ID
        rejectionReason: ''
      },
      rejectRules: {
        rejectionReason: [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' }
        ]
      },
      rejectRow: null, // 保存当前行数据
      // 提车对话框相关属性
      pickupDialogOpen: false,
      pickupRow: null, // 保存当前行数据
    };
  },
  created() {
    this.getList();
    this.getDicts();
  },
  methods: {
    /** 我要还车按钮操作 */
    handleReturnCar(row) {
      this.$modal.confirm('是否确认还车？').then(() => {
        delRecords(row.approvalRequestsId).then(response => {
          this.$modal.msgSuccess("还车成功");
          this.getList();
        }).catch(error => {
          this.$modal.msgError("还车失败");
        });
      }).catch(() => {});
    },

    /** 执行详情按钮操作 */
    handleExecuteDetail(row) {
      getRecords(row.approvalRequestsId).then(response => {
        this.executionDetailForm = {
          approvalRequestId: response.data.approvalRequestId,
          actualStartTime: response.data.actualStartTime,
          actualEndTime: response.data.actualEndTime,
          status: response.data.status,
          remarks: response.data.remarks,
          sysVechicleDto: response.data.sysVechicleDto || []
        };
        console.log(this.executionDetailForm);
        this.executionDialogTitle = "执行详情";
        this.executionDetailDialogOpen = true;
      }).catch(error => {
        this.$modal.msgError("获取执行详情失败");
      });
    },
    getStatusText(status){
      const statusItem = this.delRequestsStatus.find(item => item.dictSort === status);
      return statusItem ? statusItem.dictLabel : "未知状态";
    },
    /** 根据词典查找订单的状态 */
    getDicts() {
      getDicts('sys_shengqing_leixi').then(response => {
        this.delRequestsStatus = response.data;
      });
    },
    /** 获取审批请求详情 */
    getApproval(approvalRequestsId) {
      return getApproval(approvalRequestsId).then(response => {
        return response;
      });
    },
    /** 提车按钮操作 */
    handlePickup(row) {
      this.getApproval(row.approvalRequestsId).then(response => {
        this.pickupRow = {
          ...row,
          sysVechicleDto: response.data.sysVechicleDto || []
        };
        this.pickupDialogOpen = true; // 打开提车对话框
      }).catch(error => {
        this.$modal.msgError("获取审批请求详情失败");
      });
    },

    handlePickupSubmit(data) {
      this.$modal.confirm('是否确认提车？').then(() => {
        addRecords(data).then(response => {
          this.$modal.msgSuccess("提车成功");
          this.getList();
        }).catch(error => {
          this.$modal.msgError("提车失败");
        });
      }).catch(() => {});
    },
    handleVehicleSelection(selectedVehicles) {
      this.form.sysVehicles = selectedVehicles.map(vehicle => ({
        id: vehicle.id,
        licensePlate: vehicle.licensePlate, // 确保包含 vehiclePlate 字段
        brand: vehicle.brand
      }));
    },
    openSelectVehicleDialog() {
      this.selectVehicleDialogOpen = true;
    },
    /** 查询审批请求列表 */
    getList() {
      this.loading = true;
      listApproval(this.queryParams).then(response => {
        this.approvalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.addDialogOpen = false;
      this.detailDialogOpen = false;
      this.executionDetailDialogOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sysVehicles: [],
        requestInfo: null,
        requestDate: null,
        rejectionReason: null,
        location: null,
        driver: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addDialogOpen = true;
      this.title = "添加审批请求";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.rejectRow = row; // 保存当前行数据
      this.rejectForm.rejectionReason = ''; // 清空拒绝原因
      this.rejectDialogOpen = true; // 打开拒绝原因对话框
    },
    handleRejectSubmit() {
      this.$refs["rejectForm"].validate(valid => {
        if (valid) {
          const data = {
            id: this.rejectRow.id,
            approvalRequestsId: this.rejectRow.approvalRequestsId,
            rejectionReason: this.rejectForm.rejectionReason,
            approvalResult: '拒绝' // 假设审批结果使用 '拒绝' 表示拒绝状态
          };
          updateApproval(data).then(response => {
            this.$modal.msgSuccess("已拒绝该申请");
            this.rejectDialogOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 提交按钮 */
    handleAddSubmit() {
      this.addDialogOpen = false;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const idsStr = row.approvalRequestsId || this.ids.map(item => item.approvalRequestsId).join(",");
      this.$modal.confirm('是否确认通过审批请求编号为"' + idsStr + '"的申请？').then(() => {
        return delApproval(idsStr);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("已通过该申请");
      }).catch(() => {});
    },
    /** 查看详情按钮操作 */
    async handleDetail(row) {
      try {
        this.loading = true;
        const response = await getApproval(row.approvalRequestsId);
        this.detailForm = {
          sysProcessLogDto: response.data.sysProcessLogDto || [],
          sysVehicles: response.data.sysVechicleDto || [],
          approvalRequestsId: response.data.approvalRequestsId,
          requestInfo: response.data.requestInfo,
          requestDate: response.data.requestDate,
          approvalDate: response.data.approvalDate,
          approvalResult: response.data.approvalResult,
          rejectionReason: response.data.rejectionReason,
          requesterName: response.data.requesterName,
          approverName: response.data.approverName,
          location: response.data.location
        };
        this.detailTitle = "审批请求详情";
        this.detailDialogOpen = true;

      } catch (error) {
        this.$modal.msgError("获取审批请求详情失败");
      } finally {
        this.loading = false;
      }
    },
  }
};
</script>
